#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @License: Copyright © 2019 代鹏. All rights reserved.
# @Author: 代鹏
# @Contact: 272481080@qq.com
# @File: user_manager.py
# @Date: 2019/7/17
# @Software：cu
# @description :
from app import app
# from functools import wraps
from flask import jsonify, request, Blueprint, session
# import time, datetime, json
from datetime import timedelta
# from flask_restful import reqparse, abort, Api, Resource
# from elasticsearch import Elasticsearch
from app.server import cu_mongodb_conn
from app.server.http_beta import add_headers
# from flask import make_response

user_manager = Blueprint('user_manager', __name__)


# app.config.from_object('config')
app.config['SECRET_KEY'] = 'B0Zr98j/8yL R~XHH!jmM]LWX/,?RD'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=120)  # 配置7天有效


@user_manager.route('/login', methods=['GET', 'POST'])
def login():
    data = request.get_json()
    username = data['name']
    password = data['password']
    resp = dict()
    if username and password:
        user = cu_mongodb_conn.find_one('user', {"_id": username, "password": password, "status": 0})
        if user:
            session['username'] = username
            resp['status'] = 0
            resp['msg'] = 'ok'
        else:
            resp['status'] = 1
            resp['msg'] = 'name or password error!'
    return add_headers(jsonify(resp))


@user_manager.route('/logout', methods=['GET', 'POST'])
def logout():
    session.pop('username', None)
    resp = dict()
    resp['status'] = 0
    resp['msg'] = 'ok'
    return add_headers(jsonify(resp))


@user_manager.route('/isLogin', methods=['GET', 'POST'])
def log():
    resp = dict()
    if is_login():
        print('login')
        resp['status'] = 0
        resp['username'] = session['username']
    else:
        resp['status'] = 1
        resp['msg'] = 'no'
    return add_headers(jsonify(resp))


def is_login():
    if 'username' in session:
        return True
    else:
        return False
